import axios from 'axios';
import store from '@/store/index'
import {MessageBox, Message} from 'element-ui';

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    return config;
  },
  error => {
    // do something with request error
    console.log('request error:::',error); // for debug
    return Promise.reject(error);
  }
);


// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data;

    if (response.data.code == 303 || response.data.code == undefined || response.data.code == null) {
      //清空token 返回登录页
      store.commit('setLoginUserInfo',null);
      store.commit('setLoginTokenInfo',null);
      return Promise.reject("登录错误。");
    }

    if (response.data.code == 403) {
      Message({
        message: "无权限访问。",
        type: 'error',
        duration: 15 * 1000
      });
      history.go(-1)
      return Promise.reject("无权限访问。");
    }
    return res;
  },
  error => {
    console.log('err' + error); // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 15 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
